package com.secondriver.url.filter.urlrealm.groovy

import java.util.List;
import java.util.Map;

import com.secondriver.url.filter.urlrealm.Subject;
import com.secondriver.url.filter.urlrealm.URLBean;
import com.secondriver.url.filter.urlrealm.URLRealm;
import com.secondriver.url.filter.SysConfig;


class DefaultURLRealm implements URLRealm{

	def URLSqlQuery urlSqlQuery;

	def SysConfig sysConfig =new SysConfig();

	def tokenzie='|';
	def configSep='=';

	def DefaultURLRealm(params){
		def config=[:];
		if(params instanceof Map){
			config=params;
		}else if(params instanceof String){
			def kv=params.tokenize(this.tokenzie);
			kv.each({ str ->
				def index=str.indexOf(configSep, 0);
				if(index > 0){
					config[str.substring(0, index)]=str.substring(index+1);
				}
			})
		}else{
			throw new IllegalArgumentException(DefaultURLRealm.getClass().getName()+
			' contructor method parameter type must be Map or String.');
		}
		this.urlSqlQuery=new URLSqlQuery(config);
	}

	@Override
	public Subject buildSubject(Map<String, String> param) {
		def sessionid=param['sessionid'];
		def subjectid=param['subjectid'];
		if(null== sessionid || null == subjectid){
			throw new IllegalArgumentException(DefaultURLRealm.getClass().getName()+" method build param sessionid and subjectid must not null.");
		}
		param['status']=this.sysConfig.status.on;
		def urlbeans=this.urlSqlQuery.queryURLBean(this.sysConfig.sql.permit, param);
		def urls={ bean ->
			def v=[];
			bean.each {  it->
				v<<it.url;
			}
			return v;
		}.call(urlbeans);
		
		Subject subject=new Subject(sessionid, subjectid, urls);
		return subject;
	}
	@Override
	public List<URLBean> buildOpenURLBean() {
		def urlbeans=this.urlSqlQuery.queryURLBean(this.sysConfig.sql.open, [status:this.sysConfig.status.open]);
		return urlbeans;
	}
}
